import React, { useEffect } from 'react'
import { ScrollView, View } from '@tarojs/components'
import { useDidShow } from '@tarojs/taro'
import { SpTab, SpNote, SpToast, } from '@/components'
import { SelectInput, CommonButton } from '@/components/sp-page-components'
import { getThemeStyle, pickBy, showToast, hasNavbar } from '@/utils'
import { useSelector } from 'react-redux'
import { useImmer } from 'use-immer'
import { usePage, useDepChange } from '@/hooks'
import FilterBlock from '../../../order/list/comps/filterblock'
import doc from '@/doc'
// import { Item as GoodItem } from './comps'
import api from '@/api'
import { InfiniteScroll, CheckList } from 'antd-mobile'
import './goodsCheck.scss'
//页面类型
const PAGE_TYPE = 'goodList'

const initState = {
    //搜索框选择的参数  类型为对象
    inputParams: null,
    //搜索框输入的值
    inputValue: undefined,
    list: [],
    //tab切换
    activeIndex: 0,
    //筛选参数
    filterParams: null,
    visible: false,
    selected: [],
}

const GoodsCheck = (props) => {
    const [state, setState] = useImmer(initState)

    const { inputParams, inputValue, list, activeIndex, filterParams, visible } = state

    const {
        label,
        required = false,
        mode = 'input',
        placeholder,
        onClick = () => { },
        value: valueProp,
        onChange: onChangeProp = () => { },
        className,
        type = 'text',
        selected,
    } = props


    const handleParamChange = (inputParams) => {
        setState((_val) => {
            _val.inputParams = { ...inputParams }
        })
    }

    const {
        activeShop: { distributor_id }
    } = useSelector((state) => state.planSelection)

    const fetch = async ({ pageIndex, pageSize }) => {
        let synthetic = {}
        if (inputParams && inputValue) {
            synthetic[inputParams.value] = inputValue
        }
        let audit_status = filterParams?.approve_status ? 'approved' : undefined
        const params = {
            page: pageIndex,
            pageSize: 30,
            item_type: 'normal',
            is_warning: 0,
            is_gift: false,
            type: 0,
            distributor_id,
            audit_status,
            ...(filterParams || {}),
            ...synthetic
        }
        const { list, total_count } = await api.weapp.good_list(params)

        await setState((_val) => {
            _val.list = _val.list.concat(pickBy(list, doc.good.GOOD_LIST))
        })

        return { total: total_count }
    }

    const { page, getTotal, nextPage, resetPage, nextPageForce } = usePage({
        fetch
    })

    useDidShow(async () => {
        await setState((draft) => {
            draft.list = []
        })
        resetPage()
        console.log('useDidShow.....')
    })

    useEffect(() => {
        setState((draft) => {
            draft.list = []
        })
        resetPage()
        console.log('useDidShow.....')
    }, [valueProp])

    const handleValueChange = (inputValue) => {
        setState((_val) => {
            _val.inputValue = inputValue
        })
    }


    const handleSearchFilter = async () => {
        await setState((draft) => {
            draft.list = []
        })
        resetPage()
    }

    const handleSubmitParams = async (params) => {
        console.log('==params==', params)
        await setState((_val) => {
            _val.filterParams = params
        })
    }

    useDepChange(() => {
        if (filterParams) {
            handleSearchFilter()
        }
    }, [filterParams])


    //是否是门店
    const isStore = activeIndex === 0

    console.log('==inputParams==', inputParams, inputValue)

    return (
        <View>
            <View className='page-good-check' style={getThemeStyle()}>

                <View className='page-good-check-input'>
                    <SelectInput
                        inputParam={inputParams}
                        inputValue={inputValue}
                        pageType={PAGE_TYPE}
                        paramChange={handleParamChange}
                        valueChange={handleValueChange}
                        onInputConfirm={handleSearchFilter}
                    />
                </View>

                <FilterBlock title='商品筛选' pageType={PAGE_TYPE} onSubmitParams={handleSubmitParams} />
                <CheckList
                    className='page-good-check-list'
                    multiple
                    defaultValue={selected}
                    onChange={onChangeProp}
                >
                    {isStore && list.length > 0 ? (
                        list.map((goodInfo) => {
                            return (
                                <CheckList.Item key={goodInfo.item_id} value={JSON.stringify(goodInfo) }>
                                    {goodInfo.name}
                                </CheckList.Item>
                            )
                        })

                    ) : (
                        <SpNote className="note-list" img='empty.png'>暂无数据～</SpNote>
                    )}
                    {!!list.length && <InfiniteScroll loadMore={nextPageForce} hasMore={page.hasMore} />}

                </CheckList>
                <SpToast />
            </View>
        </View>
    )
}

export default GoodsCheck
